package com.bckj.fastboot.flow.repository.impl;

import com.bckj.fastboot.flow.model.FastProcess;
import com.bckj.fastboot.flow.repository.FastProcessRepository;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

public class DefaultFastProcessRepository implements FastProcessRepository {

    private final JdbcTemplate jdbcTemplate;

    public DefaultFastProcessRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public FastProcess getByProcessId(String processId) {
        String sql = "select * from fast_process where process_id = '%s'".formatted(processId);
        return jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {
            FastProcess fastProcess = new FastProcess();
            fastProcess.setProcessId(rs.getString("process_id"));
            fastProcess.setProcessName(rs.getString("process_name"));
            fastProcess.setContent(rs.getString("content"));
            fastProcess.setVersion(rs.getInt("version"));
            return fastProcess;
        });
    }

    @Override
    public Integer getVersionByProcessId(String processId) {
        try {
            String sql = "select version from fast_process where process_id = '%s'".formatted(processId);
            return jdbcTemplate.queryForObject(sql, (rs, rowNum) -> rs.getInt("version"));
        } catch (EmptyResultDataAccessException e) {
            throw new RuntimeException("未找到流程 processId=" + processId);
        }
    }
}
